import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/api/index.dart';
import '../../../common/api/share_api.dart';
import '../../../common/models/index.dart';
import '../../../common/services/user_service.dart';
import '../../../common/services/business_orchestration_service.dart';
import '../../../common/services/wechat_share_service.dart';
import '../../../common/routers/index.dart';
import '../../../common/utils/loading_util.dart';
import '../../../common/utils/map_launcher_util.dart';

class ActivityDetialController extends GetxController {
  ActivityDetialController();

  // 页面状态
  final RxBool isLoading = true.obs;
  final RxBool isJoining = false.obs;
  final RxString participantStatus = ''.obs;  // 🔥 参与状态：''未申请, '待审核'已申请, '已通过'已加入
  final RxBool showReportDialog = false.obs;
  
  // 🔥 好友相关状态
  final RxBool isSendingFriendRequest = false.obs;  // 是否正在发送好友申请
  
  // 🔥 实名认证状态
  final RxBool isCurrentUserVerified = false.obs;  // 当前用户是否已实名认证
  
  // 活动数据
  ActivityEntity? activity;
  int? activityId;
  String? fromPage;
  
  // 举报相关
  final RxString reportReason = ''.obs;
  final RxString selectedReportTag = ''.obs;
  final RxBool isSubmittingReport = false.obs;
  final List<String> reportTags = [
    '爽约未到场',
    '骂人',
    '中途开溜',
    '品行不端',
    '吃的太多',
  ];
  
  // 🔥 举报输入框的FocusNode
  final FocusNode reportInputFocusNode = FocusNode();

  @override
  void onInit() {
    super.onInit();
    _initParameters();
  }

  @override
  void onReady() {
    super.onReady();
    _loadActivityDetail();
    _checkCurrentUserVerification();  // 🔥 检查实名认证状态
  }

  /// 初始化路由参数
  void _initParameters() {
    try {
      debugPrint('🎯 =============== 活动详情页参数接收 ===============');
      
      final args = Get.arguments as Map<String, dynamic>?;
      
      if (args != null) {
        // 接收活动ID
        activityId = args['activityId'] as int?;
        fromPage = args['fromPage'] as String?;
        
        debugPrint('📝 活动ID: $activityId');
        debugPrint('📍 来源页面: $fromPage');
        
        // 如果传递了完整活动数据，先使用它
        final activityJson = args['activity'] as Map<String, dynamic>?;
        if (activityJson != null) {
          activity = ActivityEntity.fromJson(activityJson);
          debugPrint('✅ 从参数中获取到活动数据: ${activity!.activityTitle}');
          isLoading.value = false;
        }
      } else {
        debugPrint('⚠️ 未接收到路由参数');
        _setDefaultParameters();
      }
    } catch (e) {
      debugPrint('❌ 参数初始化失败: $e');
      _setDefaultParameters();
    }
  }

  /// 设置默认参数
  void _setDefaultParameters() {
    activityId = null;
    fromPage = 'unknown';
    isLoading.value = false;
  }

  /// 加载活动详情（🔥 始终调用接口获取实时数据）
  Future<void> _loadActivityDetail() async {
    if (activityId == null) {
      debugPrint('⚠️ 活动ID为空，无法加载详情');
      LoadingUtil.error('活动ID无效');
      return;
    }
    
    try {
      // 🔥 即使有缓存数据，也要加载最新数据
      isLoading.value = true;
      
      debugPrint('📡 开始加载活动详情，ID: $activityId');
      
      final response = await ActivityApi.getActivityDetail(
        activityId: activityId!,
      );
      
      if (response['status'] == 'success' && response['activity'] != null) {
        activity = ActivityEntity.fromJson(response['activity']);
        debugPrint('✅ 活动详情加载成功: ${activity!.activityTitle}');
      } else {
        debugPrint('❌ 活动详情加载失败: ${response['message']}');
        LoadingUtil.error(response['message'] ?? '无法加载活动详情');
      }
    } catch (e) {
      debugPrint('💥 加载活动详情异常: $e');
      LoadingUtil.error('网络错误，请重试');
    } finally {
      isLoading.value = false;
      update(['activity_detial']);
    }
  }

  /// 🔥 判断活动是否已过期
  bool get isActivityExpired {
    if (activity == null) return false;
    
    try {
      // 从 extraData 获取活动结束时间
      final extraDataMap = activity!.extraData as Map<String, dynamic>?;
      if (extraDataMap != null && extraDataMap['activityEndTime'] != null) {
        final endTimeStr = extraDataMap['activityEndTime'].toString();
        
        if (endTimeStr.isNotEmpty && endTimeStr != '时间待定') {
          final endTime = DateTime.parse(endTimeStr);
          final now = DateTime.now();
          final isExpired = now.isAfter(endTime);
          
          debugPrint('⏰ 活动时间检查:');
          debugPrint('   当前时间: $now');
          debugPrint('   结束时间: $endTime');
          debugPrint('   是否过期: $isExpired');
          
          return isExpired;
        }
      }
      
      return false;
    } catch (e) {
      debugPrint('⚠️ 解析活动结束时间失败: $e');
      return false;
    }
  }
  
  /// 加入活动
  Future<void> onJoinActivity() async {
    if (activity == null || isJoining.value || participantStatus.value.isNotEmpty) {
      return;
    }
    
    // 🔥 检查活动是否已过期
    if (isActivityExpired) {
      LoadingUtil.error('活动已结束，无法加入');
      return;
    }
    
    try {
      isJoining.value = true;
      
      debugPrint('🎯 =============== 加入活动（使用BusinessOrchestrationService） ===============');
      debugPrint('   活动: ${activity!.activityTitle}');
      debugPrint('   活动ID: ${activity!.activityId}');
      
      // 🔥 获取发布者信息
      final publisherId = activity!.publisherId;
      final activityTitle = activity!.activityTitle;
      
      if (publisherId == null) {
        debugPrint('❌ 无法获取发布者ID');
        LoadingUtil.error('活动信息不完整');
        return;
      }
      
      // 🔥 使用BusinessOrchestrationService统一入口（API + IM通知）
      final result = await BusinessOrchestrationService.to.joinActivity(
        activityId: activity!.activityId,
        publisherId: publisherId,
        activityTitle: activityTitle,
      );
      
      if (result['status'] == 'success') {
        debugPrint('✅ 加入活动成功（已自动发送IM通知给发布者）');
        
        // 🔥 更新参与状态为"待审核"（等待发布者审核）
        participantStatus.value = '待审核';
        
        LoadingUtil.success(result['message'] ?? '已申请加入，等待审核');
      } else {
        debugPrint('❌ 加入活动失败: ${result['message']}');
        LoadingUtil.error(result['message'] ?? '加入失败，请重试');
      }
    } catch (e) {
      debugPrint('💥 加入活动异常: $e');
      LoadingUtil.error('网络错误，请重试');
    } finally {
      isJoining.value = false;
    }
  }

  /// 显示举报弹窗
  void showReportModal() {
    debugPrint('🚩 显示举报弹窗');
    showReportDialog.value = true;
    reportReason.value = '';
    selectedReportTag.value = '';
    update(['activity_detial']);
  }

  /// 隐藏举报弹窗
  void hideReportModal() {
    debugPrint('🚩 隐藏举报弹窗');
    
    // 🔥 清除输入框焦点，防止键盘残留
    reportInputFocusNode.unfocus();
    
    showReportDialog.value = false;
    update(['activity_detial']);
  }

  /// 选择举报标签
  void selectReportTag(String tag) {
    if (selectedReportTag.value == tag) {
      selectedReportTag.value = '';
    } else {
      selectedReportTag.value = tag;
    }
    update(['activity_detial']);
  }

  /// 提交举报
  Future<void> submitReport() async {
    if (activity == null || isSubmittingReport.value) {
      return;
    }
    
    // 组合举报内容
    String reportText = reportReason.value.trim();
    if (selectedReportTag.value.isNotEmpty) {
      reportText = selectedReportTag.value + 
          (reportText.isNotEmpty ? ': $reportText' : '');
    }
    
    // 验证举报内容
    if (reportText.isEmpty) {
      LoadingUtil.toast('请输入举报原因或选择预设选项');
      return;
    }
    
    try {
      isSubmittingReport.value = true;
      
      debugPrint('🚩 提交举报: $reportText');
      
      // 🔥 从 UserService 获取当前用户ID
      final userService = UserService.to;
      if (!userService.isLoggedIn) {
        debugPrint('❌ 用户未登录');
        LoadingUtil.toast('请先登录后再进行举报');
        return;
      }
      
      final userId = userService.currentUserProfile?.userid;
      if (userId == null) {
        debugPrint('❌ 无法获取用户ID');
        LoadingUtil.error('请重新登录');
        return;
      }
      
      debugPrint('👤 举报者ID: $userId');
      
      final response = await ActivityApi.reportActivity(
        reporterId: userId,
        activityId: activity!.activityId,
        reportReason: reportText,
      );
      
      if (response['status'] == 'success') {
        debugPrint('✅ 举报提交成功');
        LoadingUtil.success('举报成功，我们会尽快处理');
        hideReportModal();
      } else {
        debugPrint('❌ 举报提交失败: ${response['message']}');
        LoadingUtil.error(response['message'] ?? '提交失败，请重试');
      }
    } catch (e) {
      debugPrint('💥 举报提交异常: $e');
      LoadingUtil.error('网络错误，请重试');
    } finally {
      isSubmittingReport.value = false;
    }
  }

  /// 返回上一页
  void goBack() {
    // 🔥 清除所有焦点，防止键盘在返回时弹出
    reportInputFocusNode.unfocus();
    FocusManager.instance.primaryFocus?.unfocus();
    
    Get.back();
  }
  
  /// 🔥 发布者头像点击 - 跳转到用户主页
  void onPublisherAvatarTap() {
    if (activity == null) {
      debugPrint('❌ 活动数据为空，无法跳转');
      return;
    }
    
    final publisherId = activity!.publisherId;
    if (publisherId == null) {
      debugPrint('❌ 发布者ID为空，无法跳转');
      LoadingUtil.toast('无法获取发布者信息');
      return;
    }
    
    debugPrint('👤 用户点击发布者头像，跳转到用户主页 - 发布者ID: $publisherId');
    
    // 🎯 使用 Get.toNamed 跳转到用户主页（常规页面跳转）
    Get.toNamed(
      RouteNames.myUserInfo,
      arguments: {
        'userId': publisherId,
      },
    );
  }
  
  // ==================== 好友相关方法 ====================
  
  /// 🔍 检查是否是我发布的活动
  bool get isMyActivity {
    if (activity == null) return false;
    
    final publisherId = activity!.publisherId;
    if (publisherId == null) return false;
    
    final userService = UserService.to;
    final currentUserId = userService.currentUserProfile?.userid;
    
    return currentUserId == publisherId;
  }
  
  /// 🔍 检查发布者是否是我的好友
  bool get isPublisherMyFriend {
    if (activity == null) return false;
    
    final publisherId = activity!.publisherId;
    if (publisherId == null) return false;
    
    // 🔥 检查发布者是否是当前用户自己
    final userService = UserService.to;
    final currentUserId = userService.currentUserProfile?.userid;
    if (currentUserId == publisherId) {
      return true;  // 是自己，不显示加好友按钮
    }
    
    // 🔥 检查是否在好友列表中
    return userService.isFriend(publisherId);
  }
  
  /// 🔥 发送好友申请
  Future<void> sendFriendRequest() async {
    if (activity == null || isSendingFriendRequest.value) {
      return;
    }
    
    try {
      isSendingFriendRequest.value = true;
      
      debugPrint('🤝 =============== 向活动发布者发送好友申请（使用BusinessOrchestrationService） ===============');
      
      // 获取发布者ID
      final publisherId = activity!.publisherId;
      if (publisherId == null) {
        debugPrint('❌ 发布者ID为空');
        LoadingUtil.error('无法获取发布者信息');
        return;
      }
      
      debugPrint('👤 发布者ID: $publisherId');
      
      // 🔥 显示加载提示
      LoadingUtil.show('发送好友申请中...');
      
      // 🔥 使用BusinessOrchestrationService统一入口（API + IM通知）
      final result = await BusinessOrchestrationService.to.sendFriendRequest(
        receiverId: publisherId,
        message: '通过活动详情页发送的好友申请',
        checkPermission: true,  // 启用积分权限检查
      );
      
      // 🔥 关闭加载提示
      LoadingUtil.dismiss();
      
      if (result['status'] == 'success') {
        debugPrint('✅ 好友申请发送成功（已自动发送IM通知）');
        // 🔥 不需要刷新好友申请列表，因为我发送的申请不在"收到的申请列表"中
        // 不需要更新UI，因为好友关系没有变化
      } else if (result['status'] == 'warning') {
        // 🔥 警告状态：重复发送、已是好友、被拒绝等
        debugPrint('⚠️ ${result['message']}');
        LoadingUtil.toast(result['message'] ?? '操作提示');
      } else {
        debugPrint('❌ 好友申请发送失败: ${result['message']}');
        LoadingUtil.error(result['message'] ?? '好友申请发送失败');
      }
    } catch (e) {
      // 🔥 关闭加载提示
      LoadingUtil.dismiss();
      
      debugPrint('💥 发送好友申请异常: $e');
      LoadingUtil.error('网络错误，请重试');
    } finally {
      isSendingFriendRequest.value = false;
    }
  }
  
  // ==================== 实名认证和地图导航相关方法 ====================
  
  /// 🔥 检查当前用户的实名认证状态（用于控制地址显示）
  void _checkCurrentUserVerification() {
    debugPrint('🔍 检查当前用户实名认证状态（地址显示控制）...');
    
    final userService = UserService.to;
    final currentUser = userService.currentUserProfile;
    
    if (currentUser == null) {
      debugPrint('❌ 用户未登录，地址不可见');
      isCurrentUserVerified.value = false;
      return;
    }
    
    // 检查是否已实名认证（从 extraData 中获取）
    final realNameAuth = currentUser.extraData?['realNameAuth'];
    final isVerified = realNameAuth != null && realNameAuth['verified'] == true;
    
    debugPrint('📋 当前用户实名认证状态:');
    debugPrint('   - hasRealNameAuth: ${realNameAuth != null}');
    debugPrint('   - verified: $isVerified');
    debugPrint('   - name: ${realNameAuth?['name'] ?? "未设置"}');
    
    isCurrentUserVerified.value = isVerified;
    
    if (isVerified) {
      debugPrint('✅ 当前用户已实名认证，地址可见');
    } else {
      debugPrint('⚠️ 当前用户未实名认证，地址不可见');
    }
  }
  
  /// 🗺️ 查看地图 - 显示选择菜单
  void viewMap() {
    // 🔥 检查当前用户是否已实名认证
    if (!isCurrentUserVerified.value) {
      Get.dialog(
        AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          title: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: const Color(0xFFFF6B6B).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Icon(
                  Icons.verified_user,
                  color: Color(0xFFFF6B6B),
                  size: 24,
                ),
              ),
              const SizedBox(width: 12),
              const Text(
                '实名认证提示',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          content: const Text(
            '查看活动地址需要先完成实名认证，是否前往认证？',
            style: TextStyle(
              fontSize: 15,
              color: Color(0xFF666666),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(),
              child: const Text(
                '取消',
                style: TextStyle(
                  fontSize: 15,
                  color: Color(0xFF666666),
                ),
              ),
            ),
            TextButton(
              onPressed: () {
                Get.back();
                // 🔥 跳转到实名认证页面
                Get.toNamed(RouteNames.myVerify);
              },
              style: TextButton.styleFrom(
                foregroundColor: const Color(0xFFFF6B6B),
              ),
              child: const Text(
                '去认证',
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
      );
      return;
    }
    
    // 🔥 已实名认证，显示地图选择菜单
    if (activity == null || activity!.activityLocation == null || activity!.activityLocation!.isEmpty) {
      LoadingUtil.toast('位置信息不完整');
      return;
    }
    
    // 检查是否有经纬度信息
    final hasCoordinates = activity!.latitude != null && 
                           activity!.longitude != null &&
                           activity!.latitude != 0.0 &&
                           activity!.longitude != 0.0;
    
    if (!hasCoordinates) {
      LoadingUtil.toast('位置坐标信息不完整');
      return;
    }
    
    // 🗺️ 显示地图底部弹出框
    _showMapBottomSheet();
  }
  
  /// 🗺️ 显示地图底部弹出框 - 展示所有可用地图应用供用户选择
  void _showMapBottomSheet() async {
    // 🔍 先检测所有可用的地图应用
    LoadingUtil.show('正在检测可用地图...');
    
    final availableMaps = await MapLauncherUtil.getAvailableMaps(
      latitude: activity!.latitude!,
      longitude: activity!.longitude!,
      locationName: activity!.activityLocation!,
      title: activity!.activityTitle,
    );
    
    LoadingUtil.dismiss();
    
    // 🎨 展示地图选择底部弹出框
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 🎨 顶部指示器
              Container(
                margin: const EdgeInsets.only(top: 12, bottom: 20),
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              
              // 🎨 标题区域
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFF6B6B).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: const Icon(
                        Icons.map,
                        color: Color(0xFFFF6B6B),
                        size: 24,
                      ),
                    ),
                    const SizedBox(width: 12),
                    const Expanded(
                      child: Text(
                        '选择地图应用',
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              
              const SizedBox(height: 16),
              
              // 🎨 位置信息展示
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 20),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: Colors.grey[200]!),
                ),
                child: Row(
                  children: [
                    Icon(Icons.location_on, color: Colors.grey[600], size: 20),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        activity!.activityLocation!,
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[700],
                          height: 1.4,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              
              const SizedBox(height: 20),
              
              // 🗺️ 地图应用列表
              if (availableMaps.any((map) => map.isAvailable))
                ...availableMaps.where((map) => map.isAvailable).map((mapApp) {
                  return Container(
                    margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        onTap: () async {
                          Get.back(); // 关闭弹出框
                          
                          LoadingUtil.show('正在打开${mapApp.name}...');
                          final success = await mapApp.launcher();
                          LoadingUtil.dismiss();
                          
                          if (success) {
                            LoadingUtil.success('已在${mapApp.name}中打开');
                          } else {
                            LoadingUtil.error('打开${mapApp.name}失败');
                          }
                        },
                        borderRadius: BorderRadius.circular(12),
                        child: Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey[200]!),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Row(
                            children: [
                              Container(
                                width: 48,
                                height: 48,
                                decoration: BoxDecoration(
                                  color: const Color(0xFFFF6B6B).withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                child: Icon(
                                  _getMapIcon(mapApp.icon),
                                  color: const Color(0xFFFF6B6B),
                                  size: 28,
                                ),
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                child: Text(
                                  mapApp.name,
                                  style: const TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.black87,
                                  ),
                                ),
                              ),
                              const Icon(
                                Icons.arrow_forward_ios,
                                size: 16,
                                color: Colors.grey,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  );
                }).toList()
              else
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
                  child: Column(
                    children: [
                      Icon(
                        Icons.warning_amber_rounded,
                        size: 64,
                        color: Colors.grey[400],
                      ),
                      const SizedBox(height: 12),
                      Text(
                        '未检测到可用的地图应用',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.grey[600],
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '请先安装高德地图、百度地图或其他地图应用',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[500],
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                ),
              
              const SizedBox(height: 12),
              
              // 🎨 取消按钮
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 20),
                width: double.infinity,
                child: TextButton(
                  onPressed: () => Get.back(),
                  style: TextButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    backgroundColor: Colors.grey[100],
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text(
                    '取消',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      color: Colors.grey,
                    ),
                  ),
                ),
              ),
              
              const SizedBox(height: 16),
            ],
          ),
        ),
      ),
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
    );
  }
  
  /// 🎨 根据图标名称获取对应的IconData
  IconData _getMapIcon(String iconName) {
    switch (iconName) {
      case 'navigation':
        return Icons.navigation_rounded;
      case 'map':
        return Icons.map_rounded;
      case 'location_on':
        return Icons.location_on_rounded;
      case 'public':
        return Icons.public_rounded;
      default:
        return Icons.map_rounded;
    }
  }
  
  /// 🌍 打开外部地图应用
  Future<void> _openExternalMap() async {
    try {
      final location = activity!.activityLocation!;
      final latitude = activity!.latitude ?? 0.0;
      final longitude = activity!.longitude ?? 0.0;
      
      debugPrint('🌍 准备打开外部地图应用');
      debugPrint('📍 位置: $location');
      debugPrint('🌐 坐标: $latitude, $longitude');
      
      // 🚀 使用地图启动器工具类
      await MapLauncherUtil.openMapLocation(
        latitude: latitude,
        longitude: longitude,
        locationName: location,
        title: activity!.activityTitle,
      );
      
    } catch (e) {
      debugPrint('💥 打开外部地图失败: $e');
      LoadingUtil.error('打开外部地图失败');
    }
  }
  
  // ==================== 分享相关方法 ====================
  
  /// 📤 分享活动
  Future<void> shareActivity() async {
    if (activity == null) {
      LoadingUtil.error('活动信息不完整');
      return;
    }
    
    try {
      debugPrint('📤 =============== 开始分享活动 ===============');
      debugPrint('📝 活动标题: ${activity!.activityTitle}');
      
      // 显示分享选项对话框
      _showShareDialog();
      
    } catch (e) {
      debugPrint('💥 分享活动异常: $e');
      LoadingUtil.error('分享失败');
    }
  }
  
  /// 🎨 显示分享选项对话框
  void _showShareDialog() {
    Get.dialog(
      AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: const Color(0xFF07C160).withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Icon(
                Icons.share_rounded,
                color: Color(0xFF07C160),
                size: 24,
              ),
            ),
            const SizedBox(width: 12),
            const Text(
              '分享活动',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 微信好友
            _buildShareOption(
              icon: Icons.wechat_rounded,
              label: '微信好友',
              color: const Color(0xFF07C160),
              onTap: () {
                Get.back();
                _shareToWeChat(isTimeline: false);
              },
            ),
            const SizedBox(height: 12),
            // 微信朋友圈
            _buildShareOption(
              icon: Icons.circle,
              label: '微信朋友圈',
              color: const Color(0xFF07C160),
              onTap: () {
                Get.back();
                _shareToWeChat(isTimeline: true);
              },
            ),
            const SizedBox(height: 12),
            // 复制链接
            _buildShareOption(
              icon: Icons.link_rounded,
              label: '复制链接',
              color: Colors.blue,
              onTap: () {
                Get.back();
                _copyShareLink();
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text(
              '取消',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF666666),
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  /// 🎨 构建分享选项
  Widget _buildShareOption({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onTap,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey[200]!),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Row(
            children: [
              Container(
                width: 48,
                height: 48,
                decoration: BoxDecoration(
                  color: color.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  icon,
                  color: color,
                  size: 28,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Text(
                  label,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                ),
              ),
              const Icon(
                Icons.arrow_forward_ios,
                size: 16,
                color: Colors.grey,
              ),
            ],
          ),
        ),
      ),
    );
  }
  
  /// 💬 分享到微信
  Future<void> _shareToWeChat({required bool isTimeline}) async {
    try {
      LoadingUtil.show('正在生成分享链接...');
      
      // 准备分享数据
      final activityImages = activity!.activityImages ?? [];
      final shareImages = activityImages.isNotEmpty ? activityImages : <String>[];
      
      // 🔥 调用Share API创建分享链接
      final shareResponse = await ShareApi.createActivityShare(
        activityTitle: activity!.activityTitle,
        activityText: activity!.activityDetails ?? '精彩活动等你参加！',
        activityImages: shareImages,
      );
      
      LoadingUtil.dismiss();
      
      if (shareResponse.isSuccess && shareResponse.data?.shareUrl != null) {
        final shareUrl = shareResponse.data!.shareUrl!;
        final thumbUrl = shareImages.isNotEmpty ? shareImages.first : null;
        
        debugPrint('✅ 分享链接生成成功: $shareUrl');
        debugPrint('🖼️ 缩略图URL: $thumbUrl');
        
        // 🔥 调用原生微信分享功能
        debugPrint('🚀 正在调用原生微信分享...');
        
        final success = await WeChatShareService.shareToWeChat(
          title: activity!.activityTitle,
          description: '我在玩真的发现了一个有趣的活动，快来看看吧！',
          webUrl: shareUrl,
          thumbUrl: thumbUrl,
          isTimeline: isTimeline,
        );
        
        if (success) {
          debugPrint('✅ 微信分享调起成功');
        } else {
          LoadingUtil.error('打开微信失败，请确保已安装微信');
        }
        
      } else {
        LoadingUtil.error(shareResponse.message ?? '生成分享链接失败');
      }
      
    } catch (e) {
      LoadingUtil.dismiss();
      debugPrint('💥 分享到微信失败: $e');
      LoadingUtil.error('分享失败: $e');
    }
  }
  
  /// 🔗 复制分享链接
  Future<void> _copyShareLink() async {
    try {
      LoadingUtil.show('正在生成分享链接...');
      
      // 准备分享数据
      final activityImages = activity!.activityImages ?? [];
      final shareImages = activityImages.isNotEmpty ? activityImages : <String>[];
      
      // 🔥 调用Share API创建分享链接
      final shareResponse = await ShareApi.createActivityShare(
        activityTitle: activity!.activityTitle,
        activityText: activity!.activityDetails ?? '精彩活动等你参加！',
        activityImages: shareImages,
      );
      
      LoadingUtil.dismiss();
      
      if (shareResponse.isSuccess && shareResponse.data?.shareUrl != null) {
        final shareUrl = shareResponse.data!.shareUrl!;
        
        // TODO: 复制到剪贴板
        // Clipboard.setData(ClipboardData(text: shareUrl));
        
        debugPrint('✅ 分享链接: $shareUrl');
        LoadingUtil.success('链接已复制到剪贴板\n$shareUrl');
        
      } else {
        LoadingUtil.error(shareResponse.message ?? '生成分享链接失败');
      }
      
    } catch (e) {
      LoadingUtil.dismiss();
      debugPrint('💥 复制链接失败: $e');
      LoadingUtil.error('复制失败: $e');
    }
  }
  
  @override
  void onClose() {
    // 🔥 释放FocusNode资源
    reportInputFocusNode.dispose();
    
    // 🔥 清除所有焦点，防止键盘在页面关闭时弹出
    FocusManager.instance.primaryFocus?.unfocus();
    
    super.onClose();
  }
}
